package com.dance.netty.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

/**
 * 管道处理器
 * SimpleChannelInboundHandler 继承了 ChannelInboundHandlerAdapter
 * HttpObject 客户端和服务器相互通讯的数据定义
 */
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    /**
     * 读取客户端数据
     * @param channelHandlerContext 上下文对象
     * @param msg httpObject对象
     * @throws Exception 异常
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject msg) throws Exception {
        // 判断是不是HttpRequest
        if(msg instanceof HttpRequest){

            // 进行资源过滤
            String uri = ((HttpRequest) msg).uri();
            // 如果是图标直接结束
            if(uri.endsWith("favicon.ico")){
                System.out.println("request is favicon.ico, no result");
                return;
            }

            System.out.println("msg type is " + msg.getClass());
            System.out.println("client address is " + channelHandlerContext.channel().remoteAddress());

            // 回复信息给浏览器 [HTTP协议]
            ByteBuf byteBuf = Unpooled.copiedBuffer("Hello 我是服务器~", StandardCharsets.UTF_8);

            // 构造一个HTTP的响应, 即 HttpResponse
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

            // 设置响应信息
            httpResponse.headers()
                    .set(HttpHeaderNames.CONTENT_TYPE, "text/plain;Charset=UTF-8")
                    .set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            channelHandlerContext.writeAndFlush(httpResponse);
        }
    }
}
